package cn.devcat.sso.config.security.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.devcat.sso.config.security.handler.SecurityLimitUtil;

/**
 * 重写登录认证的提交方式
 * 
 * @author huhailong
 *
 */
public class DevcatAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	public DevcatAuthenticationFilter(AuthenticationManager manager) {
		super(manager);
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		SecurityLimitUtil.checkRequestCount(request);// 限制请求频率
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
			String username = null;
			String password = null;
			try {				
				Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
				username = Optional.ofNullable((String) map.get("username")).orElse("");
				password = Optional.ofNullable((String) map.get("password")).orElse("");
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
			UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
					password);
			setDetails(request, authenticationToken);
			return this.getAuthenticationManager().authenticate(authenticationToken);
		}
		return super.attemptAuthentication(request, response);
	}

}
